"""
AI试卷生成器后端主应用
重构后的模块化架构
"""

import json
import logging
import sys
import os
from pathlib import Path

# 在导入其他模块之前加载环境变量
from dotenv import load_dotenv

# 获取项目根目录并添加到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

# 加载环境变量
env_path = project_root / ".env"
if env_path.exists():
    load_dotenv(env_path)
    print("✅ 已加载 .env 文件")
else:
    print("⚠️  未找到 .env 文件")

# 导入模块
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

from backend.config.constants import Config
from backend.api.routes import router

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('app.log', encoding='utf-8'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

# 初始化FastAPI应用
app = FastAPI(
    title="AI试卷生成器后端",
    description="基于大模型技术的AI出题工具后端服务",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc"
)

# 配置CORS
def setup_cors():
    """配置CORS中间件"""
    cors_origins = Config.CORS_ORIGINS

    if isinstance(cors_origins, str) and cors_origins.startswith("["):
        try:
            cors_origins = json.loads(cors_origins)
        except:
            cors_origins = ["*"]
    elif isinstance(cors_origins, str):
        cors_origins = [cors_origins] if cors_origins != "*" else ["*"]

    app.add_middleware(
        CORSMiddleware,
        allow_origins=cors_origins,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

# 初始化应用
def initialize_app():
    """初始化应用"""
    try:
        # 确保必要的目录存在
        Config.ensure_directories()

        # 配置CORS
        setup_cors()

        # 注册路由（不使用前缀，保持原有路径兼容性）
        app.include_router(router)

        logger.info("应用初始化成功")

    except Exception as e:
        logger.error(f"应用初始化失败: {e}")
        raise

# 应用启动事件
@app.on_event("startup")
async def startup_event():
    """应用启动事件"""
    logger.info("AI试卷生成器后端服务启动")
    # 检查API密钥是否已设置
    if Config.DASHSCOPE_API_KEY:
        logger.info("✅ DashScope API密钥已正确加载")
    else:
        logger.warning("⚠️ DashScope API密钥未设置，RAG功能将无法使用")

# 应用关闭事件
@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭事件"""
    logger.info("AI试卷生成器后端服务关闭")

# 根路径
@app.get("/")
async def root():
    """根路径"""
    return {
        "message": "AI试卷生成器后端服务",
        "version": "1.0.0",
        "docs": "/docs"
    }

# 初始化应用
initialize_app()

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "main:app",
        host="0.0.0.0",
        port=8000,
        reload=True,
        log_level="info"
    )